﻿(function () {
    jsonrpc = {
        merge: function (obj, id) {
            var ret = { request: {}, callback: {} };

            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    if (typeof (obj[key]) == 'function') {
                        ret.callback[key] = obj[key];
                    } else {
                        ret.request[key] = obj[key];
                    }
                }
            }

            if (typeof (ret.request['id']) == 'undefined') {
                ret.request['id'] = id || new Date().getTime();
            }

            if (typeof (ret.request['jsonrpc']) == 'undefined') {
                ret.request['jsonrpc'] = '2.0';
            }

            return ret;
        },

        invoke: function () {
            var args = {};
            var req = '';
            var arg = arguments[0] || {};
            var isArray = (Object.prototype.toString.call(arg) == '[object Array]');
            if (isArray) {
                var params = [];
                args = [];

                for (var i in arg) {
                    var ret = jsonrpc.merge(arg[i], i);
                    args.push(ret);
                    params.push(ret.request);
                }
                req = JSON.stringify(params);
            } else {
                args = jsonrpc.merge(arg, 0);
                req = JSON.stringify(args.request);
            }

            jQuery.support.cors = true;
            $.ajax({
                async: true,
                cache: false,
                type: 'POST',
                contentType: 'application/json;charset=utf-8',
                url: jsonrpc.uri,
                data: req,
                dataType: 'json',
                success: function (data) {
                    if (isArray) {
                        for (var i in data) {
                            if (args[i].callback['success']) {
                                args[i].callback['success'](data[i]);
                            }
                        }
                    } else {
                        if (args.callback['success']) {
                            args.callback['success'](data);
                        }
                    }
                },
                error: function (xmlHttpRequest, textStatus, errorThrown) {
                    alert(JSON.stringify(xmlHttpRequest));
                }
            });

            return this;
        }
    };

    window.jsonrpc = jsonrpc;
    window.jsonrpc.uri = 'http://' + window.location.host + ':9999/';
})();
